/**
 * @desc:标签模板
 * @author: fj
 */
import { useState, useMemo, useEffect } from "react";
import FormRender from "@/components/FormRender";
import TableRender from "@/components/TableRender";
import { useResize } from "@/hooks/useResize";
import { getFormItem } from "./config/form.js";
import { getColumns } from "./config/columns.jsx";
import {
	getTableDataOp,
	queryListTemplateSize,
	queryLabelTypeEnumList,
	updateTableDataOp,
	deleteTableDataOp,
	queryFieldManageList,
	queryLabelStoreIdList
} from "../service.js";
import { getCurrentUser } from "@/utils/authority";
import IframeEditModal from "./component/IframeEditModal.jsx";
import SelectShop from "@/components/SelectShop";
import AddCopyTemplate from "./component/AddCopyTemplate.jsx";
import SortModal from "./component/SortModal.jsx";
import EditStoreTemplate from "./component/EditStoreTemplate/EditStoreTemplate.jsx";
import PreviewModal from "./component/EditStoreTemplate/PreviewModal.jsx";
import { loadScript } from "@/utils/utils.jsx";
import { Button, message } from "antd";
import IconFont from "@/components/IconFont";
import { cloneDeep } from "lodash";

const initQuery = {};

const sizeScale = 0.7; //缩放比例

const LabelTemplate = () => {
	const [query, setQuery] = useState({ ...initQuery });

	const [data, setData] = useState([]);
	const [sizeList, setSizeList] = useState([]); //尺寸数组
	const [labelList, setLabelList] = useState([]); //标签类型
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [shopVisible, setShopVisible] = useState(false); // 店铺弹窗
	const [templateVisible, setTemplateVisible] = useState(false); // 新增复制弹窗
	const [recordData, setRecordData] = useState({}); //单行数据
	const [kuaimaiVisible, setKuaimaiVisible] = useState(false); // 快麦页面
	const [kuaiMaiItem, setKuaiMaiItem] = useState({}); //快麦item
	const [type, setType] = useState("1"); //1: 新增 2. 复制 3.编辑
	const [viewVisible, setViewVisible] = useState(false); //预览弹窗
	const [sortVisible, setSortVisible] = useState(false); //排序弹窗
	const [editStoreItem, setEditStoreItem] = useState({
		visible: false
	}); //门市打印机编辑弹窗
	const [storeIds, setStoreIds] = useState([]); //已存在的店铺id

	//监听变更
	const { el: headerEl, height: headerHeight } = useResize();

	const commonParams = useMemo(() => {
		return {
			el: "#kuaimaiiframe",
			appId: "1666316938957",
			itemsId: "400",
			libraryType: "2",
			userId: getCurrentUser()?.id + ""
		};
	}, []);

	useEffect(() => {
		if (window.KM_Template) {
			window.KMTEMPLATE = new KM_Template();
		} else {
			loadScript("https://label-open.kuaimai.com/sdk/KM_Template.umd.js").then(() => {
				window.KMTEMPLATE = new KM_Template();
			});
		}
	}, []);

	useEffect(() => {
		getTableListFunc();
	}, [query]);

	useEffect(() => {
		getListTemplateSize();
		getListLabelSort();
	}, []);

	//获取列表数据
	const getTableListFunc = async () => {
		START_LOADING();
		const params = {
			...query
		};
		if (params.size) {
			params.sizeWidth = query.size.split("-")[0];
			params.sizeHeight = query.size.split("-")[1];
		}
		params.size = undefined;
		// stageParams.current = params;
		const { data = [], success } = await getTableDataOp(params);
		if (success) {
			setData(data);
		}
		END_LOADING();
	};

	//获取模板尺寸
	const getListTemplateSize = async () => {
		const { data = [], success } = await queryListTemplateSize();
		if (success) {
			const arr = data.map(v => {
				return {
					label: `${v.sizeWidth} * ${v.sizeHeight}`,
					value: v.sizeWidth + "-" + v.sizeHeight
				};
			});
			setSizeList(arr);
		}
	};

	//获取标签类型
	const getListLabelSort = async () => {
		const { data = [], success } = await queryLabelTypeEnumList();
		if (success) {
			const arr = data.map(v => {
				return {
					label: v.templateName,
					value: v.labelType
				};
			});
			setLabelList(arr);
		}
	};

	//操作
	const handleOpera = (type, val) => {
		if (type == "edit") {
			handleEdit(val);
		} else if (type == "add") {
			handleAdd(val);
		} else if (type == "view") {
			handleView(val);
		} else if (type == "copy") {
			handleCopy(val);
		} else if (type == "del") {
			handleDelete(val);
		}
	};

	//点击编辑
	const handleEdit = record => {
		if (record.labelType == 4) {
			//门市打印
			setEditStoreItem({
				visible: true
			});
		} else {
			if (record.isDefault == 1 && record.templateAttribute == 1) {
				//默认
				KMTEMPLATE.copyTemplate({
					...commonParams,
					id: Number(record.kmTemplateCode),
					callback: res => {
						if (res) {
							setKuaimaiVisible(true);

							setKuaiMaiItem({
								ecStoreIds: record.ecStoreIds,
								templateId: Number(res),
								templateName: record.templateName,
								viewContent: record.viewContent
							});
						}
					}
				});
			} else {
				setKuaimaiVisible(true);
				setKuaiMaiItem({
					ecStoreIds: record.ecStoreIds,
					templateId: Number(record.kmTemplateCode),
					templateName: record.templateName,
					viewContent: record.viewContent
				});
			}
		}
		setRecordData(record);
		setType("2");
	};

	//点击新增
	const handleAdd = record => {
		if (record.labelType == 4) {
			//门市打印
			setEditStoreItem({
				visible: true
			});
		} else {
			setTemplateVisible(true);
		}
		setRecordData(record);
		setType("1");
	};

	//删除列表数据
	const handleDelete = async record => {
		START_LOADING();
		const { success, msg = "" } = await deleteTableDataOp({
			id: record.id
		});
		if (success) {
			message.success(msg);
			getTableListFunc();
            getListTemplateSize();
		}
		END_LOADING();
	};

	//处理返回的数据
	const handleDealData = arr => {
		const list = [];
		var obj = {};
		for (var i = 0; i < arr.length; i++) {
			obj[arr[i].key] = arr[i].name;
		}
		list.push(obj);
		return list;
	};

	//打印并且预览
	const handleView = async record => {
		if (record.labelType == 4) {
			//门市预览
			setRecordData(record);
			setViewVisible(true);
		} else {
			const { data = {}, success } = await queryFieldManageList();
			if (success) {
				const obj = {};
				// obj.zjf_order_label = handleDealData(data?.orderInfoList);
				// obj.zjf_purchase_label = handleDealData(data?.purchaseInfoList);
				// obj.zjf_library_label = handleDealData(data?.libraryInfoList);
				// obj.zjf_other_label = handleDealData(data?.otherInfoList);
				// obj.zjf_field_attribute_label = handleDealData(data?.goodsInfoList);
				obj.订单信息 = handleDealData(data?.orderInfoList);
				obj.采购单信息 = handleDealData(data?.purchaseInfoList);
				obj.入库信息 = handleDealData(data?.libraryInfoList);
				obj.其他信息 = handleDealData(data?.otherInfoList);
				obj.商品信息 = handleDealData(data?.goodsInfoList);
				KMTEMPLATE.printLabel({
					...commonParams,
					el: "#kuaimaiiframeview",
					id: Number(record.kmTemplateCode),
					data: obj
				});
			}
		}
	};

	//复制
	const handleCopy = record => {
		if (record.labelType == 4) {
			//门市打印
			setEditStoreItem({
				visible: true
			});
		} else {
			setTemplateVisible(true);
		}
		setRecordData(record);
		setType("3");
	};

	//模板名称展示input可编辑
	const handleShowInput = (record, index) => {
		const arr = cloneDeep(data);
		if (arr[index].isEdit) {
			arr[index].isEdit = false;
		} else {
            arr.map(item => item.isEdit = false);
			arr[index].isEdit = true;
		}
		setData(arr);
	};

	//修改模板名称
	const handleChangTemplateName = async (e, record, index) => {
		const val = e.target.value;
		if (val) {
			START_LOADING();
			const params = {
				...record,
				templateName: val
			};
			params.ecStoreIds =
				record.ecStoreList && record.ecStoreList.length > 0 ? record.ecStoreList.map(item => item.id).join(",") : undefined;
			const { success, msg = "" } = await updateTableDataOp(params);
			if (success) {
				message.success(msg);
				getTableListFunc();
			}
			END_LOADING();
		} else {
			message.info("模板名称不能为空");
		}
	};

	//点击修改店铺
	const handleAddStore = (text, record) => {
		getLabelStoreIdList(record, true);
	};

	//已存在的店铺
	const getLabelStoreIdList = async (record, showStore) => {
		START_LOADING();
		const { data = [], success } = await queryLabelStoreIdList({
			labelType: record.labelType
		});
		const selectStore = record.ecStoreList.map(item => item.id);
		const list = data.filter(item => !selectStore.includes(item));
		setSelectShops(record.ecStoreList);
		setStoreIds(list);
		if (showStore) {
			setShopVisible(true);
			setRecordData(record);
		}
		END_LOADING();
	};

	//修改列表店铺
	const handleEditTableListFunc = async selectedStore => {
		START_LOADING();
		const params = {
			...recordData
		};
		params.ecStoreIds = selectedStore && selectedStore.length > 0 ? selectedStore.map(item => item.id).join(",") : undefined;
		const { success } = await updateTableDataOp(params);
		if (success) {
			getTableListFunc();
			getLabelStoreIdList(recordData, false);
		}
		END_LOADING();
	};

	//表单数据
	const formArr = useMemo(() => {
		return getFormItem({
			size: sizeList,
			labelType: labelList
		});
	}, [sizeList, labelList]);

	const columns = useMemo(() => {
		return getColumns({ handleOpera, handleShowInput, handleChangTemplateName, handleAddStore });
	}, [data]);

	//表单渲染组件
	const FormRenderProps = {
		query,
		formArr,
		formConfig: {
			name: "basic-label-setting",
			style: { marginBottom: "16px" }
		},
		clickSearch(val) {
			setQuery(val);
		},
		clickReset() {
			setQuery({ ...initQuery });
		}
	};

	//表格组件
	const TableRenderProps = {
		data,
		columns,
		style: {
			height: `calc(100vh - ${headerHeight + 220}px)`
		},
		pageConfig: {
			showPage: false
		}
	};

	//店铺组件
	const SelectShopProps = {
		storeIds,
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
			handleEditTableListFunc(arr);
		}
	};

	//新增复制弹窗
	const AddCopyTemplateProps = {
		type,
		recordData,
		commonParams,
		handleCancel() {
			setTemplateVisible(false);
		},
		handleOk(val) {
			if (recordData.labelType == 4) {
				//门市打印
				setEditStoreItem({
					visible: true,
					...val
				});
			} else {
				setTemplateVisible(false);
				setKuaimaiVisible(true);
				setKuaiMaiItem(val);
			}
		}
	};

	//快麦页面
	const templateProps = {
		type,
		recordData,
		kuaiMaiItem,
		commonParams,
		handleOk() {
			getTableListFunc();
            getListTemplateSize();
			setKuaimaiVisible(false);
		},
		handleCancel() {
			setKuaimaiVisible(false);
		}
	};

	//预览弹窗 props
	const PreviewModalProps = {
		sizeScale,
		source: recordData.viewContent,
		handleCancel() {
			setViewVisible(false); //关闭 弹窗
		}
	};

	//排序弹窗
	const SortModalProps = {
		handleCancel() {
			setSortVisible(false);
		},
		handleOk() {
			getTableListFunc();
			setSortVisible(false);
		}
	};

	//门市编辑打印
	const EditStoreTemplateProps = {
		editStoreItem,
		recordData,
		type,
		handleCancel() {
			setEditStoreItem({
				visible: false
			});
			setRecordData({});
		},
		handleOk() {
			getTableListFunc();
			setEditStoreItem({
				visible: false
			});
			setRecordData({});
		}
	};

	return (
		<>
			<div id="kuaimaiiframeview" style={{ flex: 1 }}></div>
			<div ref={headerEl}>
				<FormRender {...FormRenderProps} />
			</div>
			<div className="global-page-wrap">
				<div style={{ textAlign: "right", marginBottom: "16px" }}>
					<IconFont type="icona-lujing121" />
					<Button
						onClick={() => {
							setSortVisible(true);
						}}
						type="link"
					>
						标签排序
					</Button>
				</div>
				<TableRender {...TableRenderProps} />
			</div>
			{shopVisible && <SelectShop {...SelectShopProps} />}
			{templateVisible && <AddCopyTemplate {...AddCopyTemplateProps} />}
			{kuaimaiVisible && <IframeEditModal {...templateProps} />}
			{viewVisible && <PreviewModal {...PreviewModalProps} />}
			{sortVisible && <SortModal {...SortModalProps} />}
			{editStoreItem.visible && <EditStoreTemplate {...EditStoreTemplateProps} />}
		</>
	);
};

export default LabelTemplate;
